package com.senter.data.dbflow.db;

import android.content.Context;

import net.sqlcipher.database.SQLiteDatabase;

import java.io.File;
import java.io.IOException;

/**
 * @author ice
 */
public class AppDataBaseUtils {

    /**
     * 对未加密的数据库文件做加密处理
     *
     * @param ctxt       上下文
     * @param dbName     数据库的文件名
     * @param passphrase 密码
     * @throws IOException
     */
    public static void encrypt(Context ctxt, String dbName, String passphrase) throws IOException {
        File originalFile = ctxt.getDatabasePath(dbName);

        if (originalFile.exists()) {
            File newFile =
                    File.createTempFile("sqlcipherutils", "tmp",
                            ctxt.getCacheDir());
            SQLiteDatabase db =
                    SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(),
                            "", null,
                            SQLiteDatabase.OPEN_READWRITE);

            db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';",
                    newFile.getAbsolutePath(), passphrase));
            db.rawExecSQL("SELECT sqlcipher_export('encrypted')");
            db.rawExecSQL("DETACH DATABASE encrypted;");

            int version = db.getVersion();

            db.close();

            db = SQLiteDatabase.openDatabase(newFile.getAbsolutePath(),
                    passphrase, null,
                    SQLiteDatabase.OPEN_READWRITE);
            db.setVersion(version);
            db.close();

            originalFile.delete();
            newFile.renameTo(originalFile);
        }
    }


    /**
     * 将加密数据库文件保存为非加密的数据库文件
     *
     * @param context  上下文
     * @param dbName   数据库名
     * @param password 密码
     * @param decFile  待保存的目标文件
     * @return
     */
    public static boolean decrypt(Context context, String dbName, String password, File decFile) {
        boolean flag = false;
        //先清空目标文件
        decFile.delete();
        try {
            File originalFile = context.getDatabasePath(dbName);
            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(originalFile, password, null);

            if (database.isOpen()) {
                database.rawExecSQL(String.format("ATTACH DATABASE '%s' as plaintext KEY '';", decFile.getAbsolutePath()));
                database.rawExecSQL("SELECT sqlcipher_export('plaintext');");
                database.rawExecSQL("DETACH DATABASE plaintext;");
                android.database.sqlite.SQLiteDatabase sqlDB = android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(decFile, null);
                if (sqlDB != null) {
                    flag = true;
                }
                sqlDB.close();
                database.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
        // databaseFile.delete();
    }

}
